package com.zxs.springbootexp3.controller;

import com.zxs.springbootexp3.model.RegionData;
import com.zxs.springbootexp3.service.CoronaVirusDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Controller
public class HomeController {

    @Autowired
    CoronaVirusDataService coronaVirusDataService;

    @RequestMapping("/")
    public String showData(Model model) {
        //create data list
        List<RegionData> data = coronaVirusDataService.getAllRegionData();
        List<Integer> total = coronaVirusDataService.getTotal();
        model.addAttribute("datalist", data);
        model.addAttribute("totallist", total);

        return "index";
    }

    @GetMapping("/query")
    public String queryData(@RequestParam String keyword, Model model) {

        //create data list
        List<RegionData> data = coronaVirusDataService.getAllRegionData();
        List<Integer> total = coronaVirusDataService.getTotal();
        model.addAttribute("totallist", total);

        //if keywords is not empty, get the result
        if(!"".equals(keyword)) {
            List<RegionData> res = coronaVirusDataService.queryByKeyword(data, keyword);
            model.addAttribute("datalist", res);
        }else{
            model.addAttribute("datalist", data);
        }
        return "index";
    }

}
